package com.service;

import com.dao.SendCodeDao;
import com.po.SendCodePO;
import com.util.RestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author linyukun
 * @date 2022/7/6 16:34
 */
@Service
public class SendCodeServiceImpl {
    @Autowired
    private SendCodeDao sendCodeDao;

    @Value("${image.verification.code.valid.time}")
    private String imageVerificationCodeValidTime;

    /**
     * 发送验证码
     * @author 林钰坤
     * @return
     */
    public void sendCode(String captcha, String ip) {
        int result = 0;
        SendCodePO sendCode = sendCodeDao.selectSendCode(1,ip);
        SendCodePO sendCodePo = new SendCodePO();
        sendCodePo.code = captcha;
        sendCodePo.type = 1;
        sendCodePo.typeId = ip;
        if(sendCode != null){
            result = sendCodeDao.updateSendCode(sendCodePo);
        }else {
            result = sendCodeDao.insertSendCode(sendCodePo);
        }
        if(result < 1){
            throw new RestException("sendCode失败");
        }
    }

    
     /**
       * 校验验证码
       * @author linyukun
       * @date 2022-07-06 18:31
     */
    public void checkCode(String captcha, String ip){
        int result = 0;
        SendCodePO sendCode = sendCodeDao.selectSendCode(1,ip);
        long imageVerificationCodeValidTimeLimit = new BigDecimal(this.imageVerificationCodeValidTime).intValue() * 60 * 1000L;
        if(!ObjectUtils.isEmpty(sendCode)){
            Date sendTime = sendCode.getSendTime();//发送时间
            long differTime = (sendTime.getTime()) - new Date().getTime();
            if(!sendCode.getCode().equals(captcha)){
                throw new RestException("验证码不正确");
            }
            if(differTime >= imageVerificationCodeValidTimeLimit){
                throw new RestException("验证码已过期，请重新获取验证码");
            }
        }
    }
}
